<!--
 * @Author: vera_min vera_min@163.com
 * @Date: 2025-07-11 09:21:55
 * @LastEditors: vera_min vera_min@163.com
 * @LastEditTime: 2025-07-17 22:15:00
 * @FilePath: /mail_project_destop/src/views/pi/createPI.vue
 * @Description: PI成成表单
-->
<template>
  <div class="pi-create-wrap">
    <el-card class="pi-create">
      <el-form :model="formData" :rules="rules" label-position="top" ref="formRef">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="选择邮箱" prop="email">
              <el-select v-model="formData.email" filterable placeholder="请选择邮箱" @change="emailChange">
                <el-option v-for="item in emailOptions" :key="item.account" :label="item.account"
                  :value="item.account" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <div class="header">
          <h2>PROFORMA INVOICE</h2>
        </div>
        <div class="top-section">
          <el-row :gutter="20">
            <el-col :span="12" :offset="12">
              <el-form-item label="日期" prop="createDate">
                <el-date-picker v-model="formData.createDate" type="date" placeholder="选择日期" value-format="YYYY-MM-DD"
                  style="width: 100%;" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="PI" required>
                <el-input disabled v-model="formData.pi" placeholder="自动生成" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="销售" prop="sales">
                <el-input v-model="formData.sales" placeholder="请输入销售代表" />
              </el-form-item>
            </el-col>

          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="PO#" prop="po">
                <el-input v-model="formData.po" placeholder="请输入PO#" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="公司" prop="companyCode">
                <el-input v-model="formData.companyCode" placeholder="请填写公司编码" />
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <div class="address-section">
          <h3 style="text-align: center;">客户信息</h3>
          <div v-loading="autoLoading" class="automatic">
            <div class="textareas">
              <el-input v-model="addressValue" type="textarea" placeholder="粘贴地址信息智能识别"></el-input>
            </div>
            <div class="buttons">
              <el-button type="primary" class="button" @click="automatic">智能识别</el-button>
              <span class="or">or</span>
              <el-select v-model="customValue" placeholder="选择客户自动带入信息" class="select" @change="autoImport">
                <el-option v-for="item in customData" :key="item.id" :label="item.customer" :value="item.id" />
              </el-select>
            </div>
          </div>
          <el-row :gutter="20" class="customer-info mt20">
            <el-col :span="12">
              <el-form-item label="客户名称" prop="billCustomer">
                <el-input v-model="formData.billCustomer" placeholder="请输入客户名称" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="客户公司" prop="billCompany">
                <el-input v-model="formData.billCompany" placeholder="请输入公司名称" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="客户地址" prop="billAddress">
                <el-input v-model="formData.billAddress" placeholder="请输入地址" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="客户城市" prop="billCity">
                <el-input v-model="formData.billCity" placeholder="请输入城市" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="客户电话" prop="billTel">
                <el-input v-model="formData.billTel" placeholder="请输入客户电话" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="客户邮编" prop="billZip">
                <el-input v-model="formData.billZip" placeholder="请输入邮编" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="州/省" prop="billState">
                <el-input v-model="formData.billState" placeholder="请输入州/省" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="客户邮箱" prop="billEmail">
                <el-input v-model="formData.billEmail" placeholder="请输入邮箱" />
              </el-form-item>
            </el-col>
          </el-row>
        </div>
        <el-table class="mt20" :data="formData.piItems" border style="width: 100%">
          <el-table-column prop="itemName" label="名称" />
          <el-table-column prop="itemNumber" label="编号" />
          <el-table-column prop="unitPrice" label="单价" />
          <el-table-column prop="amount" label="总金额" />
          <el-table-column prop="description" label="简介" />
          <el-table-column label="图片" width="180">
            <template #default="scope">
              <img v-for="item in scope.row.image" :key="item" :src="item" alt=""
                style="width: 100px; height: 100px;" />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="100">
            <template #default="scope">
              <el-button type="text" @click="editProduct(scope.row, scope.$index)">编辑</el-button>
              <el-button type="text" @click="deleteProduct(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-dialog v-model="showProductDialog" :title="isEditProduct ? '编辑产品信息' : '添加产品信息'" width="800px"
          :before-close="handleProductDialogClose">
          <el-form :model="productForm" :rules="productRules" label-position="top" ref="productFormRef">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="名称" label-width="80px" prop="itemName">
                  <el-input v-model="productForm.itemName" placeholder="请输入名称" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="数量" label-width="80px" prop="itemNumber">
                  <el-input v-model="productForm.itemNumber" type="number" placeholder="请输入数量" @change="calcAmount" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="单价" label-width="80px" prop="unitPrice">
                  <el-input v-model="productForm.unitPrice" type="number" placeholder="请输入单价" @change="calcAmount" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="总金额" label-width="80px" prop="amount">
                  <el-input v-model="productForm.amount" type="number" placeholder="请输入总金额" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="简介" label-width="80px" prop="description">
                  <el-input v-model="productForm.description" placeholder="请输入简介" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="图片" label-width="80px" prop="image">
                  <OneUpload v-model="productForm.image" accept="" :fileType="[]" :isShowTip="false" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>

          <template #footer>
            <span class="dialog-footer">
              <el-button @click="handleProductDialogClose">取消</el-button>
              <el-button type="primary" @click="saveProduct">保存</el-button>
            </span>
          </template>
        </el-dialog>

        <div class="address-section">
          <h3 style="text-align: center;">收件人信息</h3>
          <div class="recipient-section" style="text-align: end;">
            <el-button type="primary" @click="handleAddRecipient">
              <el-icon>
                <Plus />
              </el-icon>
              添加收件人
            </el-button>
          </div>
          <el-table class="mt20" :data="formData.shipOthersList">
            <el-table-column prop="shipConsignee" label="收货人" />
            <el-table-column prop="shipCompany" label="收货公司" />
            <el-table-column prop="shipCity" label="收货城市" />
            <el-table-column prop="shipTel" label="收货电话" />
            <el-table-column prop="shipZip" label="收货邮编" />
            <el-table-column prop="shipState" label="收货州/省" />
            <el-table-column label="操作">
              <template #default="{ row, index }">
                <el-button type="text" @click="editRecipient(row, index)">编辑</el-button>
                <el-button type="text" @click="deleteRecipient(row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-dialog v-model="showRecipientDialog" :title="isEdit ? '编辑收件人信息' : '添加收件人信息'" width="800px"
            :before-close="handleDialogClose">
            <div v-loading="autoTwoLoading" class="automatic" style="margin-top: 0px; margin-bottom: 20px;">
              <div class="textareas">
                <el-input v-model="addressValueTwo" type="textarea" placeholder="粘贴地址信息智能识别"></el-input>
              </div>
              <div class="buttons">
                <el-button type="primary" class="button" @click="automaticTwo">智能识别</el-button>
                <span class="or">or</span>
                <el-select v-model="customValueTwo" placeholder="选择客户自动带入信息" class="select" @change="autoImportTwo">
                  <el-option v-for="item in customDataTwo" :key="item.id" :label="item.customer" :value="item.id" />
                </el-select>
              </div>
            </div>
            <el-form :model="recipientForm" :rules="recipientRules" label-position="top" ref="recipientFormRef">
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="收货人" prop="shipConsignee">
                    <el-input v-model="recipientForm.shipConsignee" placeholder="请输入收货人" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="收货公司" prop="shipCompany">
                    <el-input v-model="recipientForm.shipCompany" placeholder="请输入公司名称" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="收货城市" prop="shipCity">
                    <el-input v-model="recipientForm.shipCity" placeholder="请输入城市" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="收货电话" prop="shipTel">
                    <el-input v-model="recipientForm.shipTel" placeholder="请输入电话" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="收货邮编" prop="shipZip">
                    <el-input v-model="recipientForm.shipZip" placeholder="请输入邮编" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="收货州/省" prop="shipState">
                    <el-input v-model="recipientForm.shipState" placeholder="请输入州/省" />
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>

            <template #footer>
              <span class="dialog-footer">
                <el-button @click="handleDialogClose">取消</el-button>
                <el-button type="primary" @click="saveRecipient">保存</el-button>
              </span>
            </template>
          </el-dialog>
        </div>

        <div class="shipping-section">
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="预计发货日期" prop="estimatedShipDate">
                <el-date-picker v-model="formData.estimatedShipDate" type="date" placeholder="选择预计发货日期"
                  value-format="YYYY-MM-DD" style="width: 100%;" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="预计交付日期" prop="estimatedDeliveryDate">
                <el-date-picker v-model="formData.estimatedDeliveryDate" type="date" placeholder="选择预计交付日期"
                  value-format="YYYY-MM-DD" style="width: 100%;" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="运输方式" prop="shipVia">
                <el-select v-model="formData.shipVia" placeholder="请选择运输方式" style="width: 100%;">
                  <el-option v-for="item in shippingMethods" :key="item.value" :label="item.label"
                    :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <div class="items-section">
          <h3 style="text-align: center;">产品信息</h3>
          <div class="recipient-section" style="text-align: end;">
            <el-button type="primary" @click="handleAddItem">
              <el-icon>
                <Plus />
              </el-icon>
              添加产品
            </el-button>
          </div>
          <el-table class="mt20" :data="formData.piItems" border style="width: 100%">
            <el-table-column prop="itemName" label="名称" />
            <el-table-column prop="itemNumber" label="编号" />
            <el-table-column prop="unitPrice" label="单价" />
            <el-table-column prop="amount" label="总金额" />
            <el-table-column prop="description" label="简介" />
            <el-table-column label="图片" width="180">
              <template #default="scope">
                <img v-for="item in scope.row.image" :key="item" :src="item" alt=""
                  style="width: 100px; height: 100px;" />
              </template>
            </el-table-column>
            <el-table-column label="操作" width="100">
              <template #default="scope">
                <el-button type="text" @click="editProduct(scope.row, scope.$index)">编辑</el-button>
                <el-button type="text" @click="deleteProduct(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-dialog v-model="showProductDialog" :title="isEditProduct ? '编辑产品信息' : '添加产品信息'" width="800px"
            :before-close="handleProductDialogClose">
            <el-form :model="productForm" :rules="productRules" label-position="top" ref="productFormRef">
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="名称" label-width="80px" prop="itemName">
                    <el-input v-model="productForm.itemName" placeholder="请输入名称" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="数量" label-width="80px" prop="itemNumber">
                    <el-input v-model="productForm.itemNumber" type="number" placeholder="请输入数量" @change="calcAmount" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="单价" label-width="80px" prop="unitPrice">
                    <el-input v-model="productForm.unitPrice" type="number" placeholder="请输入单价" @change="calcAmount" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="总金额" label-width="80px" prop="amount">
                    <el-input v-model="productForm.amount" placeholder="请输入总金额" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="简介" label-width="80px" prop="description">
                    <el-input v-model="productForm.description" placeholder="请输入简介" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="图片" label-width="80px" prop="image">
                    <OneUpload v-model="productForm.image" accept="" :fileType="[]" :isShowTip="false" />
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>

            <template #footer>
              <span class="dialog-footer">
                <el-button @click="handleProductDialogClose">取消</el-button>
                <el-button type="primary" @click="saveProduct">保存</el-button>
              </span>
            </template>
          </el-dialog>
        </div>

        <div class="totals-section">
          <el-row>
            <el-col :span="11">
              <el-form-item label="自定义收费金额 | $" prop="otherAmount">
                <el-input v-model="formData.otherAmount" type="number" placeholder="0" />
              </el-form-item>
            </el-col>
            <el-col :span="11" :offset="2">
              <el-form-item label="折扣 | - $" prop="discount">
                <el-input v-model="formData.discount" type="number" placeholder="0" @change="calcTotal" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="11">
              <el-form-item label="SET UP FEE | $" prop="setupCharge">
                <el-input v-model="formData.setupCharge" type="number" placeholder="0.0000" @change="calcTotal">
                  <template #suffix>
                    $
                  </template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="11" :offset="2">
              <el-form-item label="付款比例" prop="discount">
                <el-input v-model="formData.paymentTerms" :disabled="formData.paymentTermsType !== '3'"
                  placeholder="" />
                <el-radio-group v-model="formData.paymentTermsType" @change="paymentTermsTypeChange">
                  <el-radio label="100% prepaid" value="1" />
                  <el-radio label="50% Deposit and 50% Before Shipping" value="2" />
                  <el-radio label="定义义" value="3" />
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="11">
              <el-form-item label="是否显示信用卡手续费" prop="showCreditCard">
                <el-radio-group v-model="formData.showCreditCard">
                  <el-radio :value="1">是</el-radio>
                  <el-radio :value="0">否</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="11" :offset="2">
              <el-form-item label="Total" prop="total">
                <el-input v-model="formData.total" disabled placeholder="0.0000">
                  <template #suffix>
                    $
                  </template>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <div class="actions">
          <el-button @click="cancel">取消</el-button>
          <el-button type="primary" @click="submitForm">{{ route.params?.id ? '编辑PI' : '生成PI' }}</el-button>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue';
import OneUpload from '/@/components/Common/OneUpload.vue';
import { Plus } from '@element-plus/icons-vue';
import type { FormRules } from 'element-plus'
import { useRouter, useRoute } from 'vue-router';
import api from '/@/api/email/index';
import dayjs from 'dayjs'
import commonApi from '/@/api/common/index';

defineOptions({ name: 'PICreate' })

const router = useRouter();
const route = useRoute();

const formRef = ref();
const shippingMethods = ref([
  { value: 'air', label: '空运' },
  { value: 'sea', label: '海运' },
  { value: 'express', label: '快递' }
]);

console.log(route)

const isEdit = ref(false);
const productFormRef = ref();
const isEditProduct = ref(false);
const showProductDialog = ref(false);
const currentIndex = ref(0);
const currentProductIndex = ref(0);
const showRecipientDialog = ref(false);
const recipientFormRef = ref();
const recipientForm = ref({
  shipConsignee: '',// 收货人
  shipCompany: '',// 收货公司
  shipCity: '',// 收货城市
  shipZip: '',// 收货邮编
  shipState: '',// 收货州/省
  shipTel: '',// 收货电话
});

const productForm = ref({
  itemName: '',// 项目名称
  itemNumber: '',// 数量
  unitPrice: '',// 单价
  amount: '',// 总金额
  description: '',// 简介
  image: [],// 图片
});

const productRules = ref({
  itemName: [
    {
      required: true,
      message: '请输入名称',
      trigger: 'blur',
    },
  ],
  itemNumber: [
    {
      required: true,
      message: '请输入数量',
      trigger: 'blur',
    },
  ],
  unitPrice: [
    {
      required: true,
      message: '请输入单价',
      trigger: 'blur',
    },
  ],
  amount: [
    {
      required: true,
      message: '请输入总金额',
      trigger: 'blur',
    },
  ],
  description: [
    {
      required: true,
      message: '请输入简介',
      trigger: 'blur',
    },
  ],
  image: [
    {
      required: false,
      message: '请上传图片',
      trigger: 'change',
    },
  ],
})

const emailOptions = ref()
onMounted(() => {
  getEmailOptions();
  if (route.params?.id) {
    // 获取pi详情
    api.pi.detail(String(route.params.id)).then((res: any) => {
      let data = JSON.parse(JSON.stringify(res.data));
      data.piItems.forEach((item: any) => {
        item.image = item.image.split(',');
      });
      formData.value = data;
    })
  }
  getBillData()
  getShipData()
  getUserInfo()
});

const getEmailOptions = () => {
  api.pi.emailAccountList().then((res: any) => {
    emailOptions.value = res.data;
  })
}

const emailChange = (value: string) => {
  const selected = emailOptions.value.find((item: any) => item.account === value);
  if (selected) {
    formData.value.companyCode = selected.companyCode;
  }
}

const rules = reactive<FormRules<any>>({
  companyCode: [
    { required: true, message: '请选择公司', trigger: 'blur' },
  ],
  createDate: [
    {
      required: true,
      message: '请选择日期',
      trigger: 'change',
    },
  ],
  sales: [
    {
      required: true,
      message: '请输入销售代表',
      trigger: 'change',
    },
  ],
  po: [
    {
      required: true,
      message: '请输入PO#',
      trigger: 'change',
    },
  ],
  email: [
    {
      required: true,
      message: '请输入邮箱',
      trigger: 'change',
    },
  ]
})
const recipientRules = reactive<FormRules<any>>({
  shipConsignee: [
    {
      required: true,
      message: '请输入收货人',
      trigger: 'change',
    },
  ],
  shipCompany: [
    {
      required: true,
      message: '请输入收货公司',
      trigger: 'change',
    },
  ],
  shipCity: [
    {
      required: true,
      message: '请输入收货城市',
      trigger: 'change',
    },
  ],
  shipZip: [
    {
      required: true,
      message: '请输入收货邮编',
      trigger: 'change',
    },
  ],
  shipState: [
    {
      required: true,
      message: '请输入收货州/省',
      trigger: 'change',
    },
  ],
  shipTel: [
    {
      required: true,
      message: '请输入收货电话',
      trigger: 'change',
    }
  ]
});

// 表单数据
const formData = ref({
  companyCode: '',// 公司code
  createDate: dayjs().format('YYYY-MM-DD'),// 生成日期
  pi: '',// pi编号
  sales: '',  // 	销售人
  po: '',// po编号
  email: '',// 邮箱
  billCustomer: "",// 客户名称
  billCompany: "",// 客户公司
  billCity: "",// 客户城市
  billAddress: "",// 客户地址
  billTel: "",// 客户电话"
  billZip: "",// 客户邮编
  billState: "",// 客户州
  billEmail: "",// 客户邮箱
  shipOthersList: <any>[],// 其他收货信息
  // Shipping
  estimatedShipDate: '',// 预计发货日期
  estimatedDeliveryDate: '',// 预计交付日期
  shipVia: "",// 运输方式
  piItems: <any>[],// 产品信息
  otherAmount: "",// 自定义收费金额
  setupCharge: '',// SET UP FEE
  discount: '',// 折扣
  paymentTerms: '100% prepaid',
  paymentTermsType: '1',
  total: "",// 总价
  showCreditCard: 0,
});

watch(() => formData.value.piItems, () => {
  calcTotal()
}, { deep: true })

const calcTotal = () => {
  if (formData.value.piItems.length > 0) {
    let sum = 0
    formData.value.piItems.forEach((e: { amount: any; }) => {
      sum += Number(e.amount)
    });
    if (formData.value.setupCharge) {
      sum += Number(formData.value.setupCharge)
    }
    if (formData.value.discount) {
      sum -= Number(formData.value.discount)
    }
    formData.value.total = sum.toFixed(4)
  }
}
const paymentTermsTypeChange = (value: string) => {
  if (value !== '3') {
    formData.value.paymentTerms = value === '1' ? '100% prepaid' : '50% Deposit and 50% Before Shipping';
  } else {
    formData.value.paymentTerms = '';
  }
}

// 添加商品行
const handleAddItem = () => {
  productForm.value = {
    itemName: '',// 项目名称
    itemNumber: '',// 数量
    unitPrice: '',// 单价
    amount: '',// 总金额
    description: '',// 简介
    image: [],// 图片
  }
  isEditProduct.value = false;
  currentProductIndex.value = -1;
  showProductDialog.value = true;
};

const handleAddRecipient = () => {
  recipientForm.value = {
    shipConsignee: '',// 收货人
    shipCompany: '',// 收货公司
    shipCity: '',// 收货城市
    shipZip: '',// 收货邮编
    shipState: '',// 收货州/省
    shipTel: '',// 收货电话
  };
  isEdit.value = false;
  showRecipientDialog.value = true;
}

const editProduct = (row: any, index: any) => {
  productForm.value = row;
  currentProductIndex.value = index;
  isEditProduct.value = true;
  showProductDialog.value = true;
}

const deleteProduct = (row: any) => {
  ElMessageBox.confirm('确定要删除这个商品吗？', '删除确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    formData.value.piItems.splice(row, 1);
    ElMessage.success('删除成功');
  }).catch(() => {
    ElMessage.info('已取消删除');
  });
}

const editRecipient = (row: any, index: any) => {
  recipientForm.value = row;
  currentIndex.value = index;
  isEdit.value = true;
  showRecipientDialog.value = true;
}

const deleteRecipient = (row: any) => {
  ElMessageBox.confirm('确定要删除这个收件人吗？', '删除确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    const index = formData.value.shipOthersList.findIndex((item: any) => item === row);
    if (index > -1) {
      formData.value.shipOthersList.splice(index, 1);
      ElMessage.success('删除成功');
    }
  }).catch(() => {
    ElMessage.info('已取消删除');
  });
}


// 提交表单
const submitForm = () => {
  formRef.value.validate((valid: boolean) => {
    if (!valid) return ElMessage.error('表单验证失败，请检查必填项');
    // 提交表单逻辑
    console.log(formData.value)
    const data = JSON.parse(JSON.stringify(formData.value));
    data.piItems.forEach((item: any) => {
      item.image = item.image.join(',');
    });
    data.platformType = data.companyCode;
    console.log(data)

    api.pi.addOrUpdate(data).then((res: any) => {
      if (data.id) {
        ElMessage.success('PI更新成功');
      } else {
        ElMessage.success('PI生成成功');
      }
      router.push({
        path: '/PI/index'
      })
    })
  });
};

// 取消
const cancel = () => {
  router.go(-1);
};

const handleDialogClose = () => {
  showRecipientDialog.value = false;
};

const handleProductDialogClose = () => {
  showProductDialog.value = false;
};

const saveProduct = () => {
  productFormRef.value.validate((valid: boolean) => {
    if (!valid) {
      return ElMessage.error('表单验证失败，请检查必填项');
    }
    if (isEditProduct.value) {
      // 编辑
      formData.value.piItems[currentProductIndex.value] = productForm.value;
    } else {
      console.log(productForm.value);
      formData.value.piItems.push({
        itemName: productForm.value.itemName,
        itemNumber: productForm.value.itemNumber,
        unitPrice: productForm.value.unitPrice,
        amount: productForm.value.amount,
        description: productForm.value.description,
        image: productForm.value.image.map((item: any) => item.url),
      });
    }
    showProductDialog.value = false;
    console.log(formData.value);
  });
}

const saveRecipient = () => {
  recipientFormRef.value.validate((valid: boolean) => {
    if (!valid) {
      return ElMessage.error('表单验证失败，请检查必填项');
    }
    if (isEdit.value) {
      // 编辑
      formData.value.shipOthersList[currentIndex.value] = recipientForm.value;
    } else {
      formData.value.shipOthersList.push({
        shipConsignee: recipientForm.value.shipConsignee,
        shipCompany: recipientForm.value.shipCompany,
        shipCity: recipientForm.value.shipCity,
        shipZip: recipientForm.value.shipZip,
        shipState: recipientForm.value.shipState,
        shipTel: recipientForm.value.shipTel,
      });
    }

    showRecipientDialog.value = false;

  });
};
const autoLoading = ref(false)
const addressValue = ref('')
const customData: any = ref([])
const customValue = ref(null)
const automatic = async () => {
  try {
    if (!addressValue.value) {
      ElMessage.warning('请填写地址信息后识别')
      return
    }
    autoLoading.value = true
    const { data } = await api.email.operParseAddress({
      original: addressValue.value
    })
    formData.value.billCustomer = data.consignee
    formData.value.billCompany = data.company
    formData.value.billAddress = data.address
    formData.value.billCity = data.city
    formData.value.billTel = data.tel
    formData.value.billZip = data.zip
    formData.value.billState = data.state
    autoLoading.value = false
    addressValue.value = ''
  } catch (error) {
    console.log(error)
    autoLoading.value = false
  }
}
const autoImport = async () => {
  const obj = customData.value.find((item: { id: null; }) => item.id === customValue.value)
  formData.value.billCustomer = obj.customer
  formData.value.billCompany = obj.company
  formData.value.billAddress = obj.address
  formData.value.billCity = obj.city
  formData.value.billTel = obj.tel
  formData.value.billZip = obj.zip
  formData.value.billState = obj.state
}
const getBillData = async () => {
  try {
    const { data } = await api.email.getBillList()
    customData.value = data
  } catch (error) {
    console.log(error)
  }
}
const autoTwoLoading = ref(false)
const addressValueTwo = ref('')
const customDataTwo: any = ref([])
const customValueTwo = ref(null)
const automaticTwo = async () => {
  try {
    if (!addressValueTwo.value) {
      ElMessage.warning('请填写地址信息后识别')
      return
    }
    autoTwoLoading.value = true
    const { data } = await api.email.operParseAddress({
      original: addressValueTwo.value
    })
    recipientForm.value.shipConsignee = data.consignee
    recipientForm.value.shipCompany = data.company
    recipientForm.value.shipCity = data.city
    recipientForm.value.shipTel = data.tel
    recipientForm.value.shipZip = data.zip
    recipientForm.value.shipState = data.state
    autoTwoLoading.value = false
    addressValueTwo.value = ''
  } catch (error) {
    console.log(error)
    autoTwoLoading.value = false
  }
}
const autoImportTwo = async () => {
  const obj = customDataTwo.value.find((item: { id: null; }) => item.id === customValueTwo.value)
  recipientForm.value.shipConsignee = obj.consignee
  recipientForm.value.shipCompany = obj.company
  recipientForm.value.shipCity = obj.city
  recipientForm.value.shipTel = obj.tel
  recipientForm.value.shipZip = obj.zip
  recipientForm.value.shipState = obj.state
}
const getShipData = async () => {
  try {
    const { data } = await api.email.getShipList()
    customDataTwo.value = data
  } catch (error) {
    console.log(error)
  }
}
const calcAmount = () => {
  if (productForm.value.itemNumber && productForm.value.unitPrice) {
    productForm.value.amount = (Number(productForm.value.itemNumber) * Number(productForm.value.unitPrice)).toFixed(2)
  }
}

const getUserInfo = () => {
  commonApi.getUserInfo().then((res: any) => {
    if (res.code === 200) {
      formData.value.sales = res.user.nickName
    }
  })
}
</script>

<style lang="scss" scoped>
:deep(.el-form-item:not(.is-required)) {
  .el-form-item__label {
    position: relative;
    padding-left: 12px;

    &::before {
      content: "";
      position: absolute;
      left: 2px;
      top: 50%;
      transform: translateY(-50%);
      width: 4px;
      height: 16px;
      background-color: #3B7AEE;
      border-radius: 2px;
    }
  }
}

:deep(.el-dialog__footer) {
  padding: 0 20px 20px 0;
}

.pi-create-wrap {
  padding: 20px;
  background-color: #f5f7fa;
  // background-color: #fff;
  height: 100vh;
  overflow-y: scroll;

  .header {
    text-align: center;
    margin-bottom: 20px;

    h2 {
      font-size: 24px;
      font-weight: bold;
    }
  }

  .top-section,
  .address-section,
  .shipping-section,
  .items-section,
  .description-section,
  .totals-section,
  .payment-section {
    background-color: #fff;
    padding: 20px;
    margin-bottom: 20px;
    border-radius: 4px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  }

  .address-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 10px;

    h3 {
      font-size: 16px;
      font-weight: bold;
      margin: 0;
    }
  }

  .address-footer {
    display: flex;
    align-items: center;
    margin: 10px 0;

    .or {
      margin: 0 10px;
    }
  }

  .customer-info {
    // margin-top: 20px;
  }

  .price-input {
    display: flex;
    align-items: center;

    .currency {
      margin-right: 5px;
    }
  }

  .description-header {
    display: flex;
    align-items: center;
    margin-bottom: 10px;

    .el-checkbox {
      margin-right: 20px;
    }
  }

  .totals {
    padding: 10px;
    background-color: #f8f9fa;
    border-radius: 4px;
  }

  .actions {
    display: flex;
    justify-content: center;
    margin-top: 20px;

    .el-button {
      min-width: 120px;
      margin: 0 10px;
    }
  }
}

.automatic {
  margin-top: 20px;
  border: 1px dotted #ccc;
  border-radius: 8px;
  padding: 16px;

  .textareas {
    margin-bottom: 10px;
  }

  .buttons {
    display: flex;
    align-items: center;

    .or {
      margin: 0 10px;
    }

    .select {
      width: 220px;
    }
  }
}
</style>
